<template>
  <div class="caregiver-outing-container">
    <div class="header">
      <h2>外出管理</h2>
      <p>管理您负责的老人的外出申请和记录</p>
    </div>

    <!-- 搜索和筛选区域 -->
    <div class="search-section">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-input
            v-model="searchParams.elderName"
            placeholder="搜索老人姓名"
            clearable
            @clear="handleSearch"
            @keyup.enter="handleSearch"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </el-col>
        <el-col :span="6">
          <el-select
            v-model="searchParams.outingType"
            placeholder="外出类型"
            clearable
            @change="handleSearch"
          >
            <el-option label="家庭聚餐" value="家庭聚餐" />
            <el-option label="医院复查" value="医院复查" />
            <el-option label="公园散步" value="公园散步" />
            <el-option label="购物" value="购物" />
            <el-option label="亲友探访" value="亲友探访" />
            <el-option label="其他" value="其他" />
          </el-select>
        </el-col>
        <el-col :span="6">
          <el-select
            v-model="searchParams.status"
            placeholder="申请状态"
            clearable
            @change="handleSearch"
          >
            <el-option label="待审批" value="pending" />
            <el-option label="已批准" value="approved" />
            <el-option label="已拒绝" value="rejected" />
            <el-option label="已完成" value="completed" />
          </el-select>
        </el-col>
        <el-col :span="6">
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-col>
      </el-row>
    </div>

    <!-- 外出记录表格 -->
    <div class="table-section">
      <el-table
        :data="outingList"
        v-loading="loading"
        style="width: 100%"
        :default-sort="{ prop: 'createTime', order: 'descending' }"
      >
        <el-table-column prop="elderName" label="老人姓名" width="120" />
        <el-table-column prop="outingType" label="外出类型" width="120">
          <template #default="{ row }">
            <el-tag :type="getOutingTypeTag(row.outingType)">
              {{ row.outingType }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="outingReason" label="外出事由" min-width="200" show-overflow-tooltip />
        <el-table-column prop="startTime" label="开始时间" width="180">
          <template #default="{ row }">
            {{ formatDateTime(row.startTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="endTime" label="结束时间" width="180">
          <template #default="{ row }">
            {{ formatDateTime(row.endTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusTag(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="familyName" label="申请家属" width="120" />
        <el-table-column prop="createTime" label="申请时间" width="180">
          <template #default="{ row }">
            {{ formatDateTime(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button
              size="small"
              type="primary"
              link
              @click="handleViewDetail(row)"
            >
              查看详情
            </el-button>
            <el-button
              v-if="row.status === 'pending'"
              size="small"
              type="success"
              link
              @click="handleApprove(row)"
            >
              批准
            </el-button>
            <el-button
              v-if="row.status === 'pending'"
              size="small"
              type="danger"
              link
              @click="handleReject(row)"
            >
              拒绝
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-section">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 外出详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="外出申请详情"
      width="600px"
      :before-close="handleCloseDetail"
    >
      <div v-if="currentOuting" class="outing-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="老人姓名">
            {{ currentOuting.elderName }}
          </el-descriptions-item>
          <el-descriptions-item label="外出类型">
            <el-tag :type="getOutingTypeTag(currentOuting.outingType)">
              {{ currentOuting.outingType }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="外出事由" :span="2">
            {{ currentOuting.outingReason }}
          </el-descriptions-item>
          <el-descriptions-item label="开始时间">
            {{ formatDateTime(currentOuting.startTime) }}
          </el-descriptions-item>
          <el-descriptions-item label="结束时间">
            {{ formatDateTime(currentOuting.endTime) }}
          </el-descriptions-item>
          <el-descriptions-item label="申请状态">
            <el-tag :type="getStatusTag(currentOuting.status)">
              {{ getStatusText(currentOuting.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="申请家属">
            {{ currentOuting.familyName }}
          </el-descriptions-item>
          <el-descriptions-item label="家属电话">
            {{ currentOuting.familyPhone }}
          </el-descriptions-item>
          <el-descriptions-item label="申请时间">
            {{ formatDateTime(currentOuting.createTime) }}
          </el-descriptions-item>
          <el-descriptions-item label="目的地" :span="2">
            {{ currentOuting.destination || '未填写' }}
          </el-descriptions-item>
          <el-descriptions-item label="外出目的" :span="2">
            {{ currentOuting.purpose || '未填写' }}
          </el-descriptions-item>
          <el-descriptions-item label="陪同人员" :span="2">
            {{ currentOuting.companionInfo || '未填写' }}
          </el-descriptions-item>
        </el-descriptions>
      </div>
      <template #footer>
        <el-button @click="handleCloseDetail">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh } from '@element-plus/icons-vue'
import { getCaregiverOutingRecords, approveOutingApply, rejectOutingApply } from '@/api/outing.js'

// 响应式数据
const loading = ref(false)
const outingList = ref([])
const detailDialogVisible = ref(false)
const currentOuting = ref(null)

// 搜索参数
const searchParams = reactive({
  elderName: '',
  outingType: '',
  status: ''
})

// 分页参数
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 获取外出记录列表
const fetchOutingRecords = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.currentPage,
      pageSize: pagination.pageSize,
      ...searchParams
    }
    
    // 移除空值参数
    Object.keys(params).forEach(key => {
      if (params[key] === '' || params[key] === null || params[key] === undefined) {
        delete params[key]
      }
    })

    const response = await getCaregiverOutingRecords(params)
    if (response.code === 200) {
      outingList.value = response.data.records || []
      pagination.total = response.data.total || 0
    } else {
      ElMessage.error(response.msg || '获取外出记录失败')
    }
  } catch (error) {
    console.error('获取外出记录失败:', error)
    ElMessage.error('获取外出记录失败')
  } finally {
    loading.value = false
  }
}

// 搜索处理
const handleSearch = () => {
  pagination.currentPage = 1
  fetchOutingRecords()
}

// 重置搜索
const handleReset = () => {
  Object.assign(searchParams, {
    elderName: '',
    outingType: '',
    status: ''
  })
  pagination.currentPage = 1
  fetchOutingRecords()
}

// 分页大小改变
const handleSizeChange = (size) => {
  pagination.pageSize = size
  pagination.currentPage = 1
  fetchOutingRecords()
}

// 当前页改变
const handleCurrentChange = (page) => {
  pagination.currentPage = page
  fetchOutingRecords()
}

// 查看详情
const handleViewDetail = (outing) => {
  currentOuting.value = outing
  detailDialogVisible.value = true
}

// 关闭详情对话框
const handleCloseDetail = () => {
  detailDialogVisible.value = false
  currentOuting.value = null
}

// 批准外出申请
const handleApprove = async (outing) => {
  try {
    await ElMessageBox.confirm(
      `确定要批准 ${outing.elderName} 的外出申请吗？`,
      '确认批准',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    const response = await approveOutingApply(outing.applyId)
    if (response.code === 200) {
      ElMessage.success('批准成功')
      fetchOutingRecords()
    } else {
      ElMessage.error(response.msg || '批准失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('批准失败')
    }
  }
}

// 拒绝外出申请
const handleReject = async (outing) => {
  try {
    await ElMessageBox.confirm(
      `确定要拒绝 ${outing.elderName} 的外出申请吗？`,
      '确认拒绝',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    const response = await rejectOutingApply(outing.applyId)
    if (response.code === 200) {
      ElMessage.success('拒绝成功')
      fetchOutingRecords()
    } else {
      ElMessage.error(response.msg || '拒绝失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('拒绝失败')
    }
  }
}

// 获取外出类型标签样式
const getOutingTypeTag = (type) => {
  const typeMap = {
    '家庭聚餐': 'success',
    '医院复查': 'warning',
    '公园散步': 'info',
    '购物': '',
    '亲友探访': 'primary',
    '其他': 'danger'
  }
  return typeMap[type] || ''
}

// 获取状态标签样式
const getStatusTag = (status) => {
  const statusMap = {
    'pending': 'warning',
    'approved': 'success',
    'rejected': 'danger',
    'completed': 'info'
  }
  return statusMap[status] || ''
}

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    'pending': '待审批',
    'approved': '已批准',
    'rejected': '已拒绝',
    'completed': '已完成'
  }
  return statusMap[status] || status
}

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return ''
  return new Date(dateTime).toLocaleString('zh-CN')
}

// 组件挂载时获取数据
onMounted(() => {
  fetchOutingRecords()
})
</script>

<style scoped>
.caregiver-outing-container {
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.header {
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #ebeef5;
}

.header h2 {
  margin: 0;
  color: #303133;
  font-size: 20px;
}

.header p {
  margin: 5px 0 0 0;
  color: #909399;
  font-size: 14px;
}

.search-section {
  margin-bottom: 20px;
  padding: 20px;
  background: #f5f7fa;
  border-radius: 4px;
}

.table-section {
  margin-bottom: 20px;
}

.pagination-section {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

.outing-detail {
  max-height: 400px;
  overflow-y: auto;
}

:deep(.el-descriptions) {
  margin-top: 10px;
}

:deep(.el-descriptions__label) {
  font-weight: 600;
}
</style>
